<?php

/**
 * @filename source_module.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
class ctrl_trade_main extends trade_main {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();
    public static $field_value = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 	取出一条信息
     */
    public function do_detail($tm_id = '') {
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $detail = array();
        $tm_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        //DEBUG 调试输出

        if ($detail['modify_dateline']) {
            $detail['tm_success_time'] = date('Y-m-d H:i:s', $detail['modify_dateline']); //支付时间
        }
        $detail['tm_all_status'] = $detail['tm_all_status'];
        $detail['tm_all_status_name'] = mst_trade_status_all($detail['tm_all_status']);
        $detail['tm_way_name'] = trade_way($detail['tm_way']);
        if ($detail['usa_id']) {
            $detail['tm_express_way_name'] = lang('msg', 'tm_express_way_name_1');
            $detail['tm_express_status_name'] = moe_status($detail['tm_express_status']);
            $detail['tm_express_address'] = $this->get_field_value_by_id('user_shipping_address', 'usa_id', $detail['usa_id'], 'usa_user_realname,user_id,usa_user_phone,usa_address,am_id_1,am_id_2,am_id_3');
            $detail['tm_express_address']['am_id_1_name'] = $this->get_field_value_by_id('area_main', 'am_id', $detail['tm_express_address']['am_id_1'], 'am_name');
            $detail['tm_express_address']['am_id_2_name'] = $this->get_field_value_by_id('area_main', 'am_id', $detail['tm_express_address']['am_id_2'], 'am_name');
            $detail['tm_express_address']['am_id_3_name'] = $this->get_field_value_by_id('area_main', 'am_id', $detail['tm_express_address']['am_id_3'], 'am_name');
        } else {
            $detail['tm_express_way_name'] = lang('msg', 'tm_express_way_name_0');
            $detail['tm_express_way_name'] = lang('msg', 'tm_express_status_name_0');
            $detail['tm_express_address'] = '';
        }
        //DEBUG 取出订单课程信息 trade_course
        $sql = "SELECT cm_id FROM " . DB::table('trade_course') . " WHERE tm_id='" . $detail['tm_id'] . "' LIMIT 200";
        $result = DB::fetch_all($sql);
        $cm_ids = array();
        foreach ($result AS $k => $v) {
            $cm_ids[$v['cm_id']] = $v['cm_id'];
        }
        $course_info = self::get_field_value_by_id('course_main', 'cm_id', $cm_ids, 'cm_id,cm_name,user_id,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,cm_cate_id,create_dateline');
        foreach ($course_info AS $ckey => $cvalue) {
            $cvalue['so_name'] = $this->get_field_value_by_id('school_online', 'so_id', $cvalue['so_id'], 'so_name');
            $detail['tm_trade_course'][] = $cvalue;
        }
        if ($_G['gp_api']) {
            $return['code'] = '0';
            //unset($detail['tm_id']);
            //unset($detail['tm_express_address']['am_id_1']);
            //unset($detail['tm_express_address']['am_id_2']);
            //unset($detail['tm_express_address']['am_id_3']);
            //unset($detail['tm_express_address']['user_id']);
            //unset($detail['tm_express_address'][0]['cm_brief']);
            $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $detail;
            $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
            if ($client == 'pc') {
                /*
                  order: {
                  id: '1',
                  orderId: '19246500',
                  state: '7',
                  addTime: '2016-05-30 10:11:17',
                  payTime: '2016-05-30 10:11:17'
                  },
                  course: [
                  { id: '1', title: '走进电商走近淘宝', img: '/images/310.png', teacher: '教师名字（取前2位）', type: '1', times: '10', price: '100' },
                  { id: '1', title: '走进电商走近淘宝', img: '/images/310.png', teacher: '教师名字（取前2位）', type: '1', times: '10', price: '100' }
                  ]
                 */
                $detail_pc = array();
                $detail_pc['order']['id'] = $detail['tm_id'];
                $detail_pc['order']['orderId'] = $detail['tm_out_trade_no'];
                $detail_pc['order']['state'] = $detail['tm_all_status'];
                $detail_pc['order']['addTime'] = date('Y-m-d H:i:s', $detail['create_dateline']);
                $detail_pc['order']['payTime'] = date('Y-m-d H:i:s', $detail['tm_paytime']);
                $detail['create_dateline'] = $detail['create_dateline']; //下单时间
                foreach ($detail['tm_trade_course'] AS $key => $value) {
                    $tmp = array();
                    $tmp['id'] = $value['cm_id'];
                    $tmp['title'] = $value['cm_name'];
                    $tmp['img'] = $value['cm_img'];
                    $tmp['teacher'] = ext::user_realname($value['user_id']);
                    $tmp['type'] = $value['cm_cate_id'];
                    $tmp['times'] = $value['cm_hour_num'];
                    $tmp['price'] = $value['cm_price'];
                    $detail_pc['course'][] = $tmp;
                }
                $return['data'] = $detail_pc;
            }
            unset($detail['user_id']);
            //unset($detail['tm_status']);
            unset($detail['tm_trade_no']);
            unset($detail['tm_way']);
            unset($detail['tm_bank_code']);
            unset($detail['modify_dateline']);
            unset($detail['isdelete']);
            unset($detail['tm_way_name']);
            unset($detail['tm_trade_course'][0]['cm_count']);
            unset($detail['tm_trade_course'][0]['so_id']);
            unset($detail['tm_id']);
            unset($detail['create_dateline']);
            unset($detail['tm_paytime']);
            unset($detail['tm_trade_course'][0]['cm_hour_num']);
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        } else {
            include template('trade/main/detail');
        }
    }

    /*
    * 未付款订单删除接口 取消订单
    */
    public function do_close(){
        global $_G;
        
        $tm_id = isset($_REQUEST['tm_id']) && !empty($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        
        $return['code'] = '1';
        
        //1.获取订单状态
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        if($detail['tm_all_status'] != 1){//订单状态不为待付款不允许关闭
            $return['code'] = '2';
        }
        elseif($detail['tm_all_status'] == 7 || $detail['is_merge'] == 1){
            $return['code'] = '3';
        }
        elseif($detail['user_id'] != $_G['user_id']){//如果当前订单的所属人并不是当前操作者的话
            $return['code'] = '4';
        }
        else{//此处进行删除该订单操作
            $r = $this->edit('trade_main', ['tm_all_status' => 7, 'modify_dateline' => TIMESTAMP], ['tm_id' => $tm_id]);
            
            if($r){//删除成功 2016-12-16 14:47:24 根据最新文档修改状态位
                $this->edit('trade_course', ['tc_flag' => 7, 'modify_dateline' => TIMESTAMP], ['tm_id' => $tm_id]);
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 已关闭订单删除接口 删除订单
    */
    public function do_del(){
        global $_G;
        
        //2016-12-16 14:53:14 改为针对订单课程的修改
        $tc_id = isset($_REQUEST['tc_id']) && !empty($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
        
        $return['code'] = '1';
        
        //1.获取订单状态
        $detail = $this->one_info('trade_course', 'tc_id', $tc_id);
        if($detail['tc_flag'] != 7){//订单状态不为已关闭不允许删除  2016-12-16 14:54:36
            $return['code'] = '2';
        }
        elseif($detail['isdelete']){
            $return['code'] = '3';
        }
        elseif($detail['user_id'] != $_G['user_id']){//如果当前订单的所属人并不是当前操作者的话
            $return['code'] = '4';
        }
        else{//此处进行删除该订单课程操作
            $r = $this->edit('trade_course', ['tc_flag' => 8, 'modify_dateline' => TIMESTAMP], ['tc_id' => $tc_id]);
            
            if($r){//删除成功
                //2016-12-16 14:56:03 检测一下当前订单内课程是否都已处于已删除状态，如果是的话删除掉订单
                $tm_id = $detail['tm_id'];
                
                $sql_cnt = "select count(tc.tc_id) from ".DB::table('trade_course')." as tc where 1 = 1 and tc.tc_flag <> 8 and tc.tm_id = ".$tm_id;
                $cnt = DB::result_first($sql_cnt);
                
                if($cnt == 0){//说明全部都已处于删除状态，更新订单状态为已删除
                    $this->edit('trade_main', ['tm_all_status' => 8, 'modify_dateline' => TIMESTAMP], ['tm_id' => $tm_id]);
                }
                
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 前端汇款单凭证提交 API 接口
     */
    public function do_tradebill(){
        global $_G;
        
        $tb_img = isset($_REQUEST['tb_img']) && !empty($_REQUEST['tb_img']) ? $_REQUEST['tb_img'] : '';//汇款底单扫描件
        $tb_user_account = isset($_REQUEST['tb_user_account']) && !empty($_REQUEST['tb_user_account']) ? $_REQUEST['tb_user_account'] : '';//汇款用户银行账号
        $tb_user_name = isset($_REQUEST['tb_user_name']) && !empty($_REQUEST['tb_user_name']) ? $_REQUEST['tb_user_name'] : '';//汇款用户姓名
        $tb_money = isset($_REQUEST['tb_money']) && !empty($_REQUEST['tb_money']) ? $_REQUEST['tb_money'] : '';//汇款金额
        $tb_time = isset($_REQUEST['tb_time']) && !empty($_REQUEST['tb_time']) ? $_REQUEST['tb_time'] : '';//汇款时间
        $tb_mobile = isset($_REQUEST['tb_mobile']) && !empty($_REQUEST['tb_mobile']) ? $_REQUEST['tb_mobile'] : '';//汇款人手机
        $tb_other = isset($_REQUEST['tb_other']) && !empty($_REQUEST['tb_other']) ? $_REQUEST['tb_other'] : '';//其他备注信息
        $tb_trade_id = isset($_REQUEST['trade_id']) && !empty($_REQUEST['trade_id']) ? $_REQUEST['trade_id'] : '';//订单主键
        
        $tb_user_id = $_G['user_id'];
        
        $return['code'] = '1';
        
         //1.获取订单状态
        $detail = $this->one_info('trade_main', 'tm_id', $tb_trade_id);
        if($detail['tm_all_status'] != 1){//订单状态不为未付款
            $return['code'] = '2';
        }
        elseif($detail['isdelete']){//订单已删除
            $return['code'] = '3';
        }
        elseif($detail['user_id'] != $_G['user_id']){//如果当前订单的所属人并不是当前操作者的话
            $return['code'] = '4';
        }
        else{
            if(!$tb_img || !$tb_user_account || !$tb_user_name || !$tb_money || !$tb_time || !$tb_mobile || !$tb_trade_id || !$tb_user_id){//订单状态不为已付款不允许退款  未付款 退款中 已关闭
                $return['code'] = '5';
            }
            
            //组织数据加入 pre_trade_bill
            $r = $this->add('trade_bill', 
                [
                    'tb_img' => $tb_img, 
                    'tb_user_account' => $tb_user_account, 
                    'tb_user_name' => $tb_user_name, 
                    'tb_money' => $tb_money, 
                    'tb_time' => $tb_time, 
                    'tb_mobile' => $tb_mobile, 
                    'tb_other' => $tb_other, 
                    'tb_trade_id' => $tb_trade_id, 
                    'tb_user_id' => $tb_user_id, 
                    'modify_dateline' =>TIMESTAMP, 
                    'create_dateline' =>TIMESTAMP
                ]
            );
            
            if($r){
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 前端订单退款 API 接口
     */
    public function do_refund(){
        global $_G;
        
        $tm_id = isset($_REQUEST['tm_id']) && !empty($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        
        $tc_id = isset($_REQUEST['tc_id']) && !empty($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : 0;//订单课程ID号
        $tr_type = isset($_REQUEST['tr_type']) && !empty($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : 0;//退款理由
        $tr_price = isset($_REQUEST['tr_price']) && !empty($_REQUEST['tr_price']) ? $_REQUEST['tr_price'] : 0;//退款金额
        $tr_reason = isset($_REQUEST['tr_reason']) && !empty($_REQUEST['tr_reason']) ? $_REQUEST['tr_reason'] : '';//退款理由补充
        
        $return['code'] = '1';
        
        //1.获取订单状态
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        if($detail['tm_all_status'] != 2){//订单状态不为已付款不允许退款 未付款 已关闭
            $return['code'] = '2';
        }
        elseif($detail['isdelete'] || $detail['is_merge']){//2016年12月23日10:16:04 如果是用户支付的混合订单的话此处不允许
            $return['code'] = '3';
        }
        elseif($detail['user_id'] != $_G['user_id']){//如果当前订单的所属人并不是当前操作者的话
            $return['code'] = '4';
        }
        else{//此处进行申请退款该订单操作
            $tcIdArr = [];
            
            if(!$tc_id){//如果没有传递过来对应的订单课程ID
                //没有传递过来订单课程ID，即表示要退掉该订单下所有的课程
                $sql_tc = "select tc_id from ".DB::table('trade_course')." where tm_id = '{$tm_id}' and tc_flag = 2";
                $tcRes = @DB::fetch_all($sql_tc);
                foreach ($tcRes as $item) {
                    $tcIdArr[$item['tc_id']] = $item['tc_id'];
                }
            }
            else{//传递了对应的课程号ID
                //此处判断一下传递过来的课程号是否已经申请过退款
                $sql_refund = "select tr_tc_id from ".DB::table('trade_refund')." where tr_tm_id = '{$tm_id}' and tr_status in (1, 2) ";
                $refundRes = @DB::fetch_all($sql_refund);
                foreach ($refundRes as $item) {
                    $tmpArr = json_decode($item['tr_tc_id'], true);
                    
                    if(in_array($tc_id, $tmpArr)){//发现已经申请了退款
                        $return['code'] = '5';
                        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                        return false;
                    }
                }
                
                $tcIdArr[$tc_id] = $tc_id;
            }
            
            //组织数据加入 pre_trade_refund 退款表
            $r = $this->add('trade_refund', 
                    [
                        'tr_tm_id' => $tm_id,
                        'tr_so_id' => $detail['so_id'],
                        'tr_tc_id' => json_encode(array_values($tcIdArr)), 
                        'tr_user_id' => $_G['user_id'], 
                        'tr_price' => $tr_price, 
                        'tr_type' => $tr_type, 
                        'tr_reason' => $tr_reason, 
                        'ctime' =>TIMESTAMP, 
                        'mtime' =>TIMESTAMP
                    ]
                );
            
            if($r){//操作成功开始处理对应的订单表和订单课程表
                foreach ($tcIdArr as $item) {
                    $this->edit('trade_course', ['tc_flag' => 5, 'tc_type' => 1, 'modify_dateline' => TIMESTAMP], ['tc_id' => $item]);
                }
                
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 提交接口将主订单置为支付成功，将对应的订单商品置为已支付
    */
    public function do_notify(){
        global $_G;
        
        $result['success'] = true;
        
        $tm_out_trade_no = isset($_REQUEST['tm_out_trade_no']) && !empty($_REQUEST['tm_out_trade_no']) ? $_REQUEST['tm_out_trade_no'] : '';//商家订单编号
        $trade_no = isset($_REQUEST['trade_no']) && !empty($_REQUEST['trade_no']) ? $_REQUEST['trade_no'] : '';//支付宝交易编号
        
        //更新订单主表
        @DB::update('trade_main', array('tm_trade_no' => $trade_no, 'tm_status' => 'TRADE_SUCCESS', 'tm_all_status' => 2), array('tm_out_trade_no' => $tm_out_trade_no));
        //获得当前操作订单的主键
        $sql = "select tm_id from ".DB::table('trade_main')." where tm_out_trade_no = '{$tm_out_trade_no}' and isdelete = 0 limit 1";
        $tm_id = @DB::result_first($sql);
        
        $cTmIdArr[] = $tm_id;
        
        //获得当前操作订单的用户id
        $sql = "select user_id from ".DB::table('trade_main')." where tm_out_trade_no = '{$tm_out_trade_no}' and isdelete = 0 limit 1";
        $user_id = @DB::result_first($sql);
        
        $sql_is_merge = "select is_merge from ".DB::table('trade_main')." where tm_id = '{$tm_id}' limit 1";
        $is_merge = @DB::result_first($sql_is_merge);
        //此处需要判断一下该订单对应是否为=混合订单,如果是混合订单的话，此处更新对应的子订单
        if($is_merge){//走到这里说明是混合订单
            // 1.先更新所有子订单为已付款
            @DB::update('trade_main', array('tm_trade_no' => $trade_no, 'tm_status' => 'TRADE_SUCCESS', 'tm_all_status' => 2), array('pid' => $tm_id));
            // 2.获取该主订单下属对应的子订单ID
            $sql_son = "select tm_id from ".DB::table('trade_main')." where pid = '{$tm_id}' ";
            $sonRes = @DB::fetch_all($sql_son);
            if(!empty($sonRes) && is_array($sonRes)){
                foreach ($sonRes as $item) {
                    $son_tm_id = $item['tm_id'];
                    $cTmIdArr[] = $item['tm_id'];
                    @DB::update('trade_course', array('tc_flag' => 2), array('tm_id' => $son_tm_id, 'isdelete' => 0));

                    //纳入订单统计
                    $this->toCourseStatistics($son_tm_id);
                }
            }
        }
        else{//不是混合订单的话走原来流程
            //将对应的订单商品置为已支付 2016-12-16 13:50:47 根据新的文档支付成功tc_flag变为2
            @DB::update('trade_course', array('tc_flag' => 2), array('tm_id' => $tm_id, 'isdelete' => 0));

            //纳入订单统计
            $this->toCourseStatistics($tm_id);
        }
        
        //2017-6-12 10:31:22 此处加入扫表判断
        //0.获取本次订单中所有的课程
        $sql_check_course = "select cm_id from ".DB::table('trade_course')." where tm_id in (". implode("','", $cTmIdArr).") and isdelete = 0 ";
        $courseRes = @DB::fetch_all($sql_check_course);
        $cmArr = [];
        if(!empty($courseRes) && is_array($courseRes)){
            foreach($courseRes as $item){
                $cmArr[$item['cm_id']] = $item['cm_id'];
            }
        }
        
        //2017-6-13 09:19:46 此处将该订单中所有的课程对应的购买数都加1处理d
        if(!empty($cmArr) && is_array($cmArr)){
            foreach($cmArr as $item){
                $info = $this->one_info('course_main', 'cm_id', $item);
                $cnt = isset($info['cm_count']) ? $info['cm_count'] : 0;

                @DB::update('course_main', ['cm_count' => $cnt + 1], ['cm_id' => $item]);
            }
        }
        
        //复制一下课程结果集
        $cm2Arr = $cmArr;
        //扫描一下课程结果集中是否有组合课程，如果有的话查出来所有对应的子课程加入到cm2Arr结果集中去
        if(!empty($cmArr) && is_array($cmArr)){
            foreach($cmArr as $item){
                //判断一下当前课程是否是组合课程，如果是组合课程的话要查出来对应的子课程加入到$cm2Arr，如果是子课程的话要查出来组合课程的cm_id加入到$cm2Arr
                $isGroup = $this->isGroupClass($item);
                
                if($isGroup){//是组合课程
                    $sql_cg = "select cm_id as c from ".DB::table('course_group_lesson')." where cg_id = '".$item."' ";
                    $cgIdRes = @DB::fetch_all($sql_cg);
                }
                else{//不是组合课程
                    $sql_cg = "select cg_id as c from ".DB::table('course_group_lesson')." where cm_id = '".$item."' ";
                    $cgIdRes = @DB::fetch_all($sql_cg);
                }
                
                if(!empty($cgIdRes) && is_array($cgIdRes)){
                    foreach($cgIdRes as $one){
                        $cm2Arr[$one['c']] = $one['c'];
                    }
                }
            }
        }
        unset($cmArr);
        //1.扫描所有未支付订单是否含有本订单课程，如果含有的话直接关闭
        if(!empty($cm2Arr) && is_array($cm2Arr)){
            $sql_trade_nopay = "select tc_id, tm_id "
                    . " from ".DB::table('trade_course')
                    . " where cm_id in (". implode("','", $cm2Arr).") "
                    . " and tc_flag = 1 and isdelete = 0 and user_id = ".$user_id;
            $tradeRes = @DB::fetch_all($sql_trade_nopay);
            
            $tcIdArr = [];
            $tmIdArr = [];
            
            if(!empty($tradeRes) && is_array($tradeRes)){
                foreach($tradeRes as $item){
                    $tcIdArr[$item['tc_id']] = $item['tc_id'];
                    $tmIdArr[$item['tm_id']] = $item['tm_id'];
                }
            }
            
            if(!empty($tcIdArr)){//更新掉订单子表状态为已关闭
                foreach($tcIdArr as $item){
                    @DB::update('trade_course', ['tc_flag' => 7], ['tc_id' => $item]);
                }
            }
            
            if(!empty($tmIdArr)){//更新掉订单表状态为已关闭
                foreach($tmIdArr as $item){
                    @DB::update('trade_main', ['tm_all_status' => 7], ['tm_id' => $item]);
                }
            }
            
            //2.扫描购物车表，如果本订单课程中有课程还在购物车的话直接删除掉
            $wheresql = " cm_id in (".dimplode($cm2Arr).") and user_id = '".$user_id."' ";
            $this->delete("user_cart", $wheresql, 1000);
        }
        
        echo json_encode($result);
        return false;
    }
    
    /*
    * 获取订单详情接口
    */
    public function do_getinfo(){
        global $_G;
        
        $result['success'] = false;
        
        $tm_out_trade_no = isset($_REQUEST['tm_out_trade_no']) && !empty($_REQUEST['tm_out_trade_no']) ? $_REQUEST['tm_out_trade_no'] : '';
        
        $sql = "select * from ".DB::table('trade_main')." where tm_out_trade_no = '{$tm_out_trade_no}' and isdelete = 0 limit 1";
        $result['data'] = @DB::fetch_first($sql);
        
        if(!empty($result['data']) && is_array($result['data'])){
            $result['success'] = true;
        }
        
        echo json_encode($result);
        return false;
    }
    
    /*
    *  订单课程信息及优惠卷详情
    */
    public function do_orderinfo(){
        global $_G;
        
        $tm_id = isset($_REQUEST['tm_id']) && !empty($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        $nowTime = TIMESTAMP;
        
        $return['code'] = '1';
        $return['data']['order'] = array();
        $return['data']['olist'] = array();
        $return['data']['clist'] = array();
        
        //0.获取该订单详情
        $detail = $this->one_info('trade_main', 'tm_id', $tm_id);
        
        if(!$detail){
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        if($detail['modify_dateline']){
            $detail['tm_success_time'] = date('Y-m-d H:i:s', $detail['modify_dateline']); //支付时间
        }
        $detail['tm_all_status'] = $detail['tm_all_status'];
        $detail['tm_all_status_name'] = mst_trade_status_all($detail['tm_all_status']);
        $detail['tm_way_name'] = trade_way($detail['tm_way']);
        
        $detail_pc = array();
        $detail_pc['order']['id'] = $detail['tm_id'];
        $detail_pc['order']['orderId'] = $detail['tm_out_trade_no'];
        $detail_pc['order']['state'] = $detail['tm_all_status'];
        $detail_pc['order']['addTime'] = $detail['create_dateline'] ? date('Y-m-d H:i:s', $detail['create_dateline']) : '';
        $detail_pc['order']['payTime'] = $detail['tm_paytime'] ? date('Y-m-d H:i:s', $detail['tm_paytime']) : '';
        $detail_pc['order']['create_dateline'] = $detail['create_dateline']; //下单时间
        $detail_pc['order']['times'] = $detail['create_dateline'] + 48*3600 - TIMESTAMP; //剩余倒计时
        
        $tmIdArr = [];
        //获取该订单所有的tm_id
        if($detail['is_merge']){//说明是合并订单
            //获取该订单对应的子订单tm_id
            $sql_tm = "select tm_id from ".DB::table('trade_main')." where pid = '".$tm_id."' ";
            $tmIdRes = @DB::fetch_all($sql_tm);

            if(!empty($tmIdRes) && is_array($tmIdRes)){
                foreach ($tmIdRes as $item) {
                    $tmIdArr[] = $item['tm_id'];
                }
            }
        }
        else{//非合并订单
            $tmIdArr[] = $tm_id;
        }
       
        //DEBUG 取出订单课程信息 trade_course
        $sql = "select cm_id from ".DB::table('trade_course')." where tm_id in (".dimplode($tmIdArr).") limit 500";
        $result = DB::fetch_all($sql);
        $cm_ids = array();
        foreach ($result as $v) {
            $cm_ids[$v['cm_id']] = $v['cm_id'];
        }
        
        $course_info = self::get_field_value_by_id('course_main', 'cm_id', $cm_ids, 'cm_id,cm_name,user_id,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,cm_cate_id,create_dateline');
        if(!empty($course_info) && is_array($course_info)){
            foreach ($course_info as $cvalue) {
                $cvalue['cm_img']=$cvalue['cm_img'];
                $cvalue['so_name'] = $this->get_field_value_by_id('school_online', 'so_id', $cvalue['so_id'], 'so_name');
                $detail['tm_trade_course'][] = $cvalue;
            }
        }
        
        if(!empty($detail['tm_trade_course']) && is_array($detail['tm_trade_course'])){
            foreach ($detail['tm_trade_course'] as $value) {
                $tmp = array();
                $tmp['id'] = $value['cm_id'];
                $tmp['title'] = $value['cm_name'];
                $tmp['img'] = $value['cm_img'];
                $tmp['teacher'] = ext::user_realname($value['user_id']);
                $tmp['type'] = $value['cm_cate_id'];
                $tmp['times'] = $value['cm_hour_num'];
                $tmp['price'] = $value['cm_price'];
                $detail_pc['olist'][] = $tmp;
            }
        }
        
        $return['data'] = $detail_pc;
        
        //2.根据用户user_id获取可用优惠卷信息
        $user_id = $_G['user_id'];

        $sql_coupon = "select U.`cu_id`, C.`cc_title`, C.`cc_img_small`, C.`cc_cate_id`, C.`cc_min_cost`, C.`cc_value` "
                . " from ".DB::table('coupon_use')." as U "
                . " left join ".DB::table('coupon_code')." as C on C.cc_id = U.cc_id "
                . " where U.cu_owner_user_id = '{$user_id}' and U.isdelete = 0 and C.isdelete = 0 "
                . " and C.cc_start_dateline <= {$nowTime} and C.cc_end_dateline > {$nowTime} ";
        $return['data']['clist'] = @DB::fetch_all($sql_coupon);
        //如果获取到了订单内容的话说明请求成功
        if(!empty($return['data']['order']) && is_array($return['data']['order'])){
            $return['code'] = '0';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 购物车点击结算按钮 
    */
    public function do_settlement(){
        global $_G;
        
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';
        //2016-09-09 13:47:44 新修改
        $is_success = false;
        if($_G['user_id'] && !empty($cm_id) && is_array($cm_id)){//如果用户已登陆
            //2017-6-12 10:03:06
            //此处判断一下这些课程是否有效，如果无效的话阻止掉后续操作
            //需要先过滤一下传递过来的课程数组中是否有课程不存
            $isHas = true;
            foreach($cm_id as $item){
                $isHas = $this->isHasCmId($item);
                
                if(!$isHas){
                    break;
                }
            }
            
            if(!$isHas){
                $return['code'] = '3';//存在不能购买的课程 无效 或 已下架 或 不在购买时间范围内
                echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                return false;
            }
            
            $isBuy = false;
            foreach($cm_id as $item){
                $isBuy = $this->isBuyCmId($_G['user_id'], $item);
                
                if($isBuy){
                    break;
                }
            }
            
            if($isBuy){
                $return['code'] = '4';//存在课程已购买
                echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                return false;
            }
            
            $c_user_id = $_G['user_id'];
            $c_tm_out_trade_no = '0512'.date('YmdHis').rand(1000, 9999);
            $c_status = 'WAIT_BUYER_PAY';
            $c_time = TIMESTAMP;
            
            //2016-12-21 09:24:43 对传递过来的cm_id数组进行网校判断
            $soArr = [];//网校集合
            if(!empty($cm_id) && is_array($cm_id)){
                foreach($cm_id as $item){
                    $soIdTmp = $this->cmIdToSoId($item);
                    $soArr[$soIdTmp]['cmId'][] = $item;
                }
            }
            
            $soCnt = count($soArr);
            //主订单创建
            //如果此时的网校集合内网校数量大于1的话说明该订单将会是一张混合订单，需要进行拆分订单处理
            if($soCnt > 1){
                $tm_id = $this->newTrade($cm_id, $c_user_id, $c_tm_out_trade_no, $c_status, $c_time, 0, 1);
                //此处进行子订单的生成
                foreach($soArr as $k => $v){
                    $so_id = sprintf("%08d", $k);
                    $this->newTrade($v['cmId'], $c_user_id, $c_tm_out_trade_no.$so_id, $c_status, $c_time, $tm_id, 0);
                }
            }
            else{//只有一张订单不需要拆分此处加入网校so_id
                $tm_id = $this->newTrade($cm_id, $c_user_id, $c_tm_out_trade_no, $c_status, $c_time, 0, 0);
            }
            
            if($tm_id){//生成了订单主键号
                $is_success = true;
            }
        }
        
        if($is_success){
            $return['code'] = '0';
            $return['data']['tm_id'] = $tm_id;
        }
        else{
            $return['code'] = '1';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     *  添加订单
     */
    public function do_add(){
        global $_G;
        
        $trade_main = isset($_REQUEST['trade_main']) && !empty($_REQUEST['trade_main']) ? $_REQUEST['trade_main'] : '';
        //2016-09-09 08:33:01 新修改
        $is_success = false;
        
        if($_G['user_id']){//如果用户已登陆
            $trade_main['user_id'] = $_G['user_id'];
            $trade_main['tm_out_trade_no'] = '0512'.date('YmdHis').rand(1000, 9999);
            $trade_main['tm_status'] = 'WAIT_BUYER_PAY';
            //根据折扣 购买课程 计算总价
            $sql = "SELECT SUM(cm_price) FROM ".DB::table('course_main')." WHERE cm_id IN (".dimplode($trade_main['cm_id']).") LIMIT 1";
            $trade_main['tm_total_fee'] = @DB::result_first($sql);
            //DEBUG 折扣优惠计算
            if($trade_main['cu_id']){//如果传递进来了优惠卷的编号
                $data = array('cu_id' => $trade_main['cu_id']);
                $check_result = auto_mad('coupon', 'use', 'check', $data); //校验优惠券
                
                $check_result_array = json_decode($check_result, true);
                
                if(isset($check_result_array['code']) && ($check_result_array['code'] == 0)){
                    //进行优惠券折扣处理
                    if(3 == $check_result_array['data']['coupon_code']['cc_cate_id']){
                        //折扣优惠券
                        $trade_main['tm_total_fee'] = ceil($trade_main['tm_total_fee'] * 100 * $check_result_array['data']['coupon_code']['cc_value']) / 100;
                    }
                    else{
                        //现金优惠券
                        $trade_main['tm_total_fee'] = $trade_main['tm_total_fee'] - $check_result_array['data']['coupon_code']['cc_value'];
                    }
                    //现金抵扣后如果为赋值,最小支付为0.01
                    if($trade_main['tm_total_fee'] <= 0){
                        $trade_main['tm_total_fee'] = 0.01;
                    }
                }
                else{
                    echo $check_result;
                    die; //优惠券无效
                }
            }
            
            $trade_main['create_dateline'] = TIMESTAMP;
            $cu_id = $trade_main['cu_id'];
            $cm_id = $trade_main['cm_id'];
            unset($trade_main['cm_id']);
            unset($trade_main['cu_id']);
            $tm_id = $this->add('trade_main', $trade_main, true);
            //DEBUG 添加选课记录
            $i = 0;
            if(!empty($cm_id) && is_array($cm_id)){
                foreach($cm_id AS $value){
                    $course_main = $this->one_info('course_main', 'cm_id', $value);
                    $data = array(
                        'user_id' => $_G['user_id'],
                        'cm_id' => $value,
                        'group_cm_id' => 0,
                        'cm_price' => $course_main['cm_price'],
                        'tc_flag' => 0,
                        'tc_type' => 0,
                        'tm_id' => $tm_id,
                        'tc_applicant' => 0,
                        'tc_take_handout' => 0
                    );
                    $insert_tc_id = DB::insert('trade_course', $data, true);
                    if($insert_tc_id){
                        $i++;
                    }
                }
            }
            
            unset($trade_main['cm_id']);
            //DEBUG 插入用户选课和订单记录
            $count_trade_main_cm_id = count($cm_id);//校验选课完整性
            //更新优惠券已使用
            if($tm_id && $cu_id){//传入优惠卷信息才更新
                DB::update('coupon_use', array('tm_id' => $tm_id, 'cu_status' => 1), array('cu_id' => $cu_id));
            }
            
            $data = $trade_main;
            $data['tm_id'] = $tm_id;
            //DEBUG 记录日志
            $insert_id = DB::insert('trade_log', $data, true);
            
            if($insert_id && $tm_id && $i == $count_trade_main_cm_id){
                $is_success = true;
            }
        }
        
        if($is_success){
            $return['code'] = '0';
            $data['create_dateline'] = date('Y-m-d H:i:s', TIMESTAMP);
            $data['pay_url'] = substr($_G['siteurl'], 0, -1).':'.$_G['siteport'].'/index.php?mod=trade&action=main&do=commit&api=json';
            $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $data;
        }
        else{
            $return['code'] = '1';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }

    /*
    * 需要增加一个独立接口 就是 前端给出课程编号和token 平台接口判断返回 这个课程用户是否已经购买 code
    */
    public function do_checktrade(){
        global $_G;
        
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';
        
        $is_success = false;
        if($_G['user_id'] && $cm_id){//如果用户已登陆 并且提交过来选课编号 2016-12-16 09:07:01 根据新的定义 tc_flag 2 为已付款不需要结合tc_type判断
            $sql_check = "select count(*) as cnt from ".DB::table('trade_course')." where user_id = '".$_G['user_id']."' and cm_id = '".$cm_id."' and tc_flag = 2 and isdelete = 0 ";
            $cnt = @DB::result_first($sql_check);
            
            if($cnt){//说明存在该用户的购买记录
                $is_success = true;
            }
            else{//如果当时没有直接找到，可能是存在当初购买的是一个组合课程，此时需要去查询一下该课程编号对应的组合课程号码，并判断用户是否已经购买了组合课程
                // 该情况下传入的cm_id需要通过 pre_course_group_lesson 关联表获取真实的组合课程cg_id，一个cm_id可能会对应多个cg_id
                $sql_cg = "select cg_id from ".DB::table('course_group_lesson')." where cm_id = '".$cm_id."' ";
                
                $cgIdRes = @DB::fetch_all($sql_cg);
                
                $cgIdArr = [];
                if(!empty($cgIdRes) && is_array($cgIdRes)){
                    foreach ($cgIdRes as $item) {
                        $cgIdArr[$item['cg_id']] = $item['cg_id'];
                    }
                }
                
                if(!empty($cgIdArr) && is_array($cgIdArr)){
                    $sql_res = "select count(*) as cnt "
                            . " from ".DB::table('trade_course')." "
                            . " where user_id = '".$_G['user_id']."' and cm_id in ('".implode("', '", $cgIdArr)."') and tc_flag = 2 and isdelete = 0 ";
                    $cnt = @DB::result_first($sql_res);
                    if($cnt){//说明存在该用户的购买记录
                        $is_success = true;
                    }
                }
            }
        }
        
        if($is_success){
            $return['code'] = '0';
        }
        else{
            $return['code'] = '1';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 前端需要一个共免费选课的接口，前端提供用户token和课程编号，后端直接生成订单和选课记录 并返回成功状态
    */
    public function do_freetrade(){
        global $_G;
        
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';
        
        $is_success = false;
        $user_id = $_G['user_id'];
        if($_G['user_id'] && !empty($cm_id) && is_array($cm_id)){//如果用户已登陆 并且提交过来选课编号
            //2017-6-12 10:03:06
            //此处判断一下这些课程是否有效，如果无效的话阻止掉后续操作
            //需要先过滤一下传递过来的课程数组中是否有课程不存
            $isHas = true;
            foreach($cm_id as $item){
                $isHas = $this->isHasCmId($item);
                
                if(!$isHas){
                    break;
                }
            }
            
            if(!$isHas){
                $return['code'] = '3';//存在不能购买的课程 无效 或 已下架 或 不在购买时间范围内
                echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                return false;
            }
            
            $isBuy = false;
            foreach($cm_id as $item){
                $isBuy = $this->isBuyCmId($_G['user_id'], $item);
                
                if($isBuy){
                    break;
                }
            }
            
            if($isBuy){
                $return['code'] = '4';//存在课程已购买
                echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                return false;
            }
            
            
            $c_user_id = $_G['user_id'];
            $c_tm_out_trade_no = '0512'.date('YmdHis').rand(1000, 9999);
            $c_status = 'TRADE_SUCCESS';
            $c_time = TIMESTAMP;
            
            //2016-12-21 09:24:43 对传递过来的cm_id数组进行网校判断
            $soArr = [];//网校集合
            if(!empty($cm_id) && is_array($cm_id)){
                foreach($cm_id as $item){
                    $soIdTmp = $this->cmIdToSoId($item);
                    $soArr[$soIdTmp]['cmId'][] = $item;
                }
            }
            
            $soCnt = count($soArr);
            //主订单创建
            //如果此时的网校集合内网校数量大于1的话说明该订单将会是一张混合订单，需要进行拆分订单处理
            if($soCnt > 1){
                //此处进行子订单的生成
                foreach($soArr as $k => $v){
                    $so_id = sprintf("%08d", $k);
                    $tm_id = $this->newTrade($v['cmId'], $c_user_id, $c_tm_out_trade_no.$so_id, $c_status, $c_time, 0, 0, 1);
                    $this->toCourseStatistics($tm_id);
                }
            }
            else{//只有一张订单不需要拆分此处加入网校so_id
                $tm_id = $this->newTrade($cm_id, $c_user_id, $c_tm_out_trade_no, $c_status, $c_time, 0, 0, 1);
                $this->toCourseStatistics($tm_id);
            }
            
            $is_success = true;
        }
        
        if($is_success){
            $return['code'] = '0';
            
            //2017-6-13 09:19:46 此处将该订单中所有的课程对应的购买数都加1处理d
            if(!empty($cm_id) && is_array($cm_id)){
                foreach($cm_id as $item){
                    $info = $this->one_info('course_main', 'cm_id', $item);
                    $cnt = isset($info['cm_count']) ? $info['cm_count'] : 0;
                    
                    @DB::update('course_main', ['cm_count' => $cnt + 1], ['cm_id' => $item]);
                }
            }
            
            //2017-6-12 10:31:22 此处加入扫表判断
            //0.获取本次订单中所有的课程
            //复制一下课程结果集
            $cm2Arr = $cmArr = $cm_id;
            //扫描一下课程结果集中是否有组合课程，如果有的话查出来所有对应的子课程加入到cm2Arr结果集中去
            if(!empty($cmArr) && is_array($cmArr)){
                foreach($cmArr as $item){
                    //判断一下当前课程是否是组合课程，如果是组合课程的话要查出来对应的子课程加入到$cm2Arr，如果是子课程的话要查出来组合课程的cm_id加入到$cm2Arr
                    $isGroup = $this->isGroupClass($item);

                    if($isGroup){//是组合课程
                        $sql_cg = "select cm_id as c from ".DB::table('course_group_lesson')." where cg_id = '".$item."' ";
                        $cgIdRes = @DB::fetch_all($sql_cg);
                    }
                    else{//不是组合课程
                        $sql_cg = "select cg_id as c from ".DB::table('course_group_lesson')." where cm_id = '".$item."' ";
                        $cgIdRes = @DB::fetch_all($sql_cg);
                    }

                    if(!empty($cgIdRes) && is_array($cgIdRes)){
                        foreach($cgIdRes as $one){
                            $cm2Arr[$one['c']] = $one['c'];
                        }
                    }
                }
            }
            unset($cmArr);
            //1.扫描所有未支付订单是否含有本订单课程，如果含有的话直接关闭
            if(!empty($cm2Arr) && is_array($cm2Arr)){
                $sql_trade_nopay = "select tc_id, tm_id "
                        . " from ".DB::table('trade_course')
                        . " where cm_id in (". implode("','", $cm2Arr).") "
                        . " and tc_flag = 1 and isdelete = 0 and user_id = ".$user_id;
                $tradeRes = @DB::fetch_all($sql_trade_nopay);

                $tcIdArr = [];
                $tmIdArr = [];

                if(!empty($tradeRes) && is_array($tradeRes)){
                    foreach($tradeRes as $item){
                        $tcIdArr[$item['tc_id']] = $item['tc_id'];
                        $tmIdArr[$item['tm_id']] = $item['tm_id'];
                    }
                }

                if(!empty($tcIdArr)){//更新掉订单子表状态为已关闭
                    foreach($tcIdArr as $item){
                        @DB::update('trade_course', ['tc_flag' => 7], ['tc_id' => $item]);
                    }
                }

                if(!empty($tmIdArr)){//更新掉订单表状态为已关闭
                    foreach($tmIdArr as $item){
                        @DB::update('trade_main', ['tm_all_status' => 7], ['tm_id' => $item]);
                    }
                }

                //2.扫描购物车表，如果本订单课程中有课程还在购物车的话直接删除掉
                $wheresql = " cm_id in (".dimplode($cm2Arr).") and user_id = '".$user_id."' ";
                $this->delete("user_cart", $wheresql, 1000);
            }
        }
        else{
            $return['code'] = '1';
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
    * 处理提交过来的订单请求
    */
    public function do_commit(){
        global $_G;
        $tm_id = isset($_REQUEST['tm_id']) && !empty($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : 0;//订单主键ID
        $tm_way = isset($_REQUEST['tm_way']) && !empty($_REQUEST['tm_way']) ? $_REQUEST['tm_way'] : 0;//支付方式：1 支付宝 2 人工收款 3 支付宝网银支付
        $tm_bank_code = isset($_REQUEST['tm_bank_code']) && !empty($_REQUEST['tm_bank_code']) ? $_REQUEST['tm_bank_code'] : 0;//银行简码
        $cu_id = isset($_REQUEST['cu_id']) && !empty($_REQUEST['cu_id']) ? $_REQUEST['cu_id'] : 0;//优惠卷编码
        
        $uri = isset($_REQUEST['uri']) && !empty($_REQUEST['uri']) ? $_REQUEST['uri'] : '';//前端传递过来的同步跳转地址
        
        $return['code'] = '1';
        
        if($tm_id){//传递过来了订单主键ID
            //先获取订单对应详情
            $orderInfo = $this->one_info('trade_main', 'tm_id', $tm_id);
            
            if(!empty($orderInfo) && is_array($orderInfo)){//查询到对应订单
                $user_id = $orderInfo['user_id'];
                $tm_out_trade_no = $orderInfo['tm_out_trade_no'];
                $tm_total_price = $orderInfo['tm_total_price'];
                $tm_total_fee = $orderInfo['tm_total_fee'];
                $tm_status = $orderInfo['tm_status'];
                $isdelete = $orderInfo['isdelete'];
                
                if(!$isdelete && ($tm_status == 'WAIT_BUYER_PAY')){//订单已删除、状态不为等待支付
                    //此处获取优惠卷信息
                    //DEBUG 折扣优惠计算
                    if($cu_id){//如果传递进来了优惠卷的编号
                        $data = array('cu_id' => $cu_id);
                        $check_result = auto_mad('coupon', 'use', 'check', $data); //校验优惠券

                        $check_result_array = json_decode($check_result, true);
                        if(isset($check_result_array['code']) && ($check_result_array['code'] == 0)){
                            //进行优惠券折扣处理
                            if(3 == $check_result_array['data']['coupon_code']['cc_cate_id']){
                                //折扣优惠券
                                $tm_total_fee = ceil($tm_total_price * 100 * $check_result_array['data']['coupon_code']['cc_value']) / 100;
                            }
                            else{
                                //现金优惠券
                                $tm_total_fee = $tm_total_price - $check_result_array['data']['coupon_code']['cc_value'];
                            }
                            //现金抵扣后如果为赋值,最小支付为0.01
                            if($tm_total_fee <= 0){
                                $tm_total_fee = 0.01;
                            }
                            
                            //此处需要反向更新订单主表的优惠信息
                            @DB::update('trade_main', array('tm_youhui' => ($tm_total_price - $tm_total_fee), 'tm_total_fee' => $tm_total_fee), array('tm_id' => $tm_id));
                            //此处更新该优惠卷为已使用 cu_status = 1 tm_id = $tm_id  pre_coupon_use
                            @DB::update('coupon_use', array('cu_status' => 1, 'tm_id' => $tm_id), array('cu_id' => $cu_id));
                        }
                        else{//优惠卷无效
                            $return['code'] = '2';
                            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                            return false;
                        }
                    }
                    //根据user_id获取该用户的学校名称、班级名称和真实姓名
                    $detail = $this->one_info('user_detail', 'user_id', $user_id);
                    $u_name = $detail['user_realname'] ? $detail['user_realname'] : $detail['user_nickname'];
                    //该学生学校编号 班级编号
                    $sdetail = $this->one_info('school_main', 'sm_id', $detail['sm_id']);
                    $s_name = $sdetail['sm_name'];
                    $cdetail = $this->one_info('class_main', 'class_id', $detail['class_id']);
                    $c_name = $cdetail['class_name'];
                    //如果支付方式选择是支付宝
                    if($tm_way == 1){
                        @DB::update('trade_main', array('tm_way' => $tm_way), array('tm_id' => $tm_id));
                        @DB::update('trade_main', array('tm_way' => $tm_way), array('pid' => $tm_id));
                        
                        wconfig('alipay_conf', array('return_url' => $uri));
                        
                        require_once(SITE_ROOT."openapi/alipay/alipay.config.php");
                        require_once(SITE_ROOT."openapi/alipay/lib/alipay_submit.class.php");
                        $parameter = array(
                            "service"           => $alipay_config['service'],
                            "partner"           => $alipay_config['partner'],
                            "seller_id"         => $alipay_config['seller_id'],
                            "payment_type"	=> $alipay_config['payment_type'],
                            "notify_url"	=> $alipay_config['notify_url'],
                            "return_url"	=> $alipay_config['return_url'],

                            "anti_phishing_key" =>$alipay_config['anti_phishing_key'],
                            "exter_invoke_ip"   =>$alipay_config['exter_invoke_ip'],
                            "out_trade_no"	=> $tm_out_trade_no,//商户订单号，商户网站订单系统中唯一订单号，必填
                            "subject"           => '[支付宝-嘉兴智慧教育在线课堂]['.$s_name.']['.$c_name.']['.$u_name.'][网上支付]['.$tm_out_trade_no.']',//订单名称，必填
                            "total_fee"         => $tm_total_fee,//付款金额，必填
                            "body"              => '',//商品描述，可空
                            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
                        );

                        //建立请求
                        $alipaySubmit = new AlipaySubmit($alipay_config);
                        $return['data']['url'] = $alipaySubmit->buildRequestUri($parameter);
                        
                        $return['code'] = '0';
                    }
                    elseif($tm_way == 2){//如果选择2表示人工收款包括汇款
                        @DB::update('trade_main', array('tm_way' => $tm_way), array('tm_id' => $tm_id));
                        @DB::update('trade_main', array('tm_way' => $tm_way), array('pid' => $tm_id));
                        
                        $return['code'] = '0';
                    }
                    else{
                        $return['code'] = '3';
                        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
                        return false;
                    }
                }
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     *  编辑系统信息
     */

    public function do_edit() {
        global $_G;
        $issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit'] : '';
        $trade_main = isset($_REQUEST['trade_main']) && !empty($_REQUEST['trade_main']) ? $_REQUEST['trade_main'] : '';
        $tm_id = isset($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        if ($tm_id) {
            if ('1' == $issubmit) {
                $trade_main['modify_dateline'] = TIMESTAMP;
                //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
                //foreach($trade_main AS $key => $value){
                //    if(is_array($value) && !empty($value)){
                //        $trade_main[$key] = implode(",", $value);
                //    }
                //}                
                $where = array('tm_id' => $tm_id);
                $effect_row = $this->edit('trade_main', $trade_main, $where);
                if ($effect_row) {
                    showmessage('操作成功', 'index.php?mod=trade&action=main&do=index');
                } else {
                    showmessage('操作失败', 'index.php?mod=trade&action=main&do=index');
                }
            } else {
                //DEBUG 获取操作对象信息
                $info = $this->one_info('trade_main', 'tm_id', $tm_id);
                include template('trade/main/edit');
            }
        } else {
            showmessage('请选择编辑对象', 'index.php?mod=trade&action=main&do=index');
        }
    }

    /*
     *  删除系统信息
     */

    public function do_delete() {
        global $_G;
        $tm_id = isset($_REQUEST['tm_id']) ? $_REQUEST['tm_id'] : '';
        if ($tm_id) {
            $effect_row = $this->delete("trade_main", array("tm_id" => $tm_id), $limit = 1);
            if ($effect_row) {
                showmessage('操作成功', 'index.php?mod=trade&action=main&do=index');
            } else {
                showmessage('操作失败', 'index.php?mod=trade&action=main&do=index');
            }
        }
    }

    /*
     *  订单列表
     */
    public function do_tradelist() {
        global $_G;
        //处理传递参数
        $status = isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : 0;//查询状态 0.全部 1.未付款 2.已付款 3.退款中 4.已关闭
        
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';//tm_out_trade_no
        $tm_evaluate = isset($_REQUEST['tm_evaluate']) ? $_REQUEST['tm_evaluate'] : '';//订单是否评价
        
        $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
        
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : 6;
        $start = (($page - 1) * $limit);
//        $wheresql = " where tm.isdelete = 0 and tm.is_free = 0 and tm.user_id = '".$_G['user_id']."' and tm.is_merge = 0 ";//2016-12-22 08:57:02 改为取出所有的非混合订单
        $wheresql = " where tm.isdelete = 0 and tm.user_id = '".$_G['user_id']."' and tm.is_merge = 0 ";//2016-12-22 08:57:02 改为取出所有的非混合订单

        
        if($keyword){//如果传递过来订单编号
            $wheresql.= " and tm.tm_out_trade_no like '%".$keyword."%' ";
        }
        
        if($tm_evaluate){//是否已评价过滤
            $wheresql.= " and tm.tm_evaluate = '".$tm_evaluate."' ";
        }
        
        //如果传递过来的查询状态不是全部 
        if($status == 1){//1.未付款 tc_flag = 1
            $wheresql.= " and tc.tc_flag = 1 ";
        }
        elseif($status == 2){//2.已付款 tc_flag = 2
            $wheresql.= " and tc.tc_flag = 2 ";
        }
        elseif($status == 3){//3.退款中 tc_flag = 5
            $wheresql.= " and tc.tc_flag = 5 ";
        }
        elseif($status == 4){//4.已关闭 tc_flag = 7
            $wheresql.= " and tc.tc_flag = 7 ";
        }
        else{//查询全部 0.返回所有tc_type状态不为8的数据
            $wheresql.= " and tc.tc_flag <> 8 ";
        }
        
        $orderby = " order by tm.tm_id desc ";
        
        $sql_info = "select tm.*, cm.*, cm.user_id as t_user_id, tc.*, tc.create_dateline as dateline "
                . " from ".DB::table('trade_course')." as tc "
                . " left join ".DB::table('course_main')." as cm on tc.cm_id = cm.cm_id "
                . " left join ".DB::table('trade_main')." as tm on tc.tm_id = tm.tm_id "
                .$wheresql.$orderby. DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "select count(*) from ".DB::table('trade_course')." as tc "
                . " left join ".DB::table('trade_main')." as tm on tc.tm_id = tm.tm_id ".$wheresql;
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        $page_result = [
            'page_now'   => $page,
            'total_page' => ceil($sql_total_rows_result / $limit),
            'total_rows' => $sql_total_rows_result,
            'page_data'  => $sql_info_result
        ];
        
        $return['code'] = '0';
        if($client == 'pc'){
            $order = [];
            //DEBUG 格式化PC输出
            foreach ($page_result['page_data'] as $value) {
                //课程详情部分不变
                $tmp = [];
                $tmp['id'] = $value['cm_id'];
                $tmp['tc_id'] = $value['tc_id'];
                $tmp['title'] = $value['cm_name'];
                $tmp['img'] = $value['cm_img'];
                $tmp['teacher'] = ext::user_realname($value['t_user_id']);
                $tmp['type'] = $value['cm_cate_id'];
                $tmp['cm_price'] = $value['cm_price'];
                $tmp['tc_flag'] = $value['tc_flag'];
                $tmp['tc_type'] = $value['tc_type'];
                //课程订单部分
                $temp = [];
                $temp['id'] = $value['tm_id'];
                $temp['num'] = $value['tm_out_trade_no'];
                
                $temp['tm_state'] = $value['tm_all_status'];
                $temp['time'] = date('Y-m-d H:i:s', $value['dateline']);
                $temp['create_dateline'] = $value['dateline'];
                $temp['tm_total_fee'] = $value['tm_total_fee'];
                $temp['course'] = $tmp;
                $order[] = $temp;
            }
            $page_result['page_data'] = $order;
            $return['data'] = $page_result;
        }
        else{
            $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $page_result;
        }
        
        echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     *  系统信息列表
     */

    public function do_index() {
        global $_G;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : '6';
        $start = (($page - 1) * $perpage);
        $wheresql = " WHERE tm.isdelete=0 AND tm.user_id='".$_G['user_id']."' ";
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        if ($keyword) {
            $wheresql = " AND tm.tm_out_trade_no LIKE '%" . $keyword . "%' ";
        }
        $tm_evaluate = isset($_REQUEST['tm_evaluate']) ? $_REQUEST['tm_evaluate'] : '';
        if ($tm_evaluate) {
            $wheresql .= " AND tm.tm_evaluate = '" . $tm_evaluate . "' ";
        }
        $tm_all_status = isset($_REQUEST['tm_all_status']) ? $_REQUEST['tm_all_status'] : '';
        if ($tm_all_status) {
            $wheresql .= " AND tm.tm_all_status = '" . $tm_all_status . "' ";
        }
        $orderby = " ORDER BY tm.tm_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
          $page_result = array(
          //int 返回结果总数
          'total_rows' => $total_rows,
          //array 一页数据数组
          'page_data' => $page_data
          );
         */
        //DEBUG 获取信息
        /*
        $page_result = $this->index('trade_main', $page_condition, 'tm_id,tm_total_fee,tm_out_trade_no,tm_trade_no,tm_status,tm_way,usa_id,tm_express_number,tm_express_status,tm_evaluate,modify_dateline,create_dateline,tm_all_status');
        foreach ($page_result['page_data'] AS $key => $value) {
            $trade_main_create_dateline =  $page_result['page_data'][$key]['create_dateline'];
            $page_result['page_data'][$key]['create_dateline'] = date('Y-m-d H:i:s', $page_result['page_data'][$key]['create_dateline']); //下单时间
            if ($page_result['page_data'][$key]['modify_dateline']) {
                $page_result['page_data'][$key]['tm_success_time'] = date('Y-m-d H:i:s', $page_result['page_data'][$key]['modify_dateline']); //支付时间
            }
            $page_result['page_data'][$key]['tm_status_name'] = mst_trade_status($page_result['page_data'][$key]['tm_status']);
            $page_result['page_data'][$key]['tm_way_name'] = trade_way($page_result['page_data'][$key]['tm_way']);
            if ($page_result['page_data'][$key]['usa_id']) {
                $page_result['page_data'][$key]['tm_express_way_name'] = lang('msg', 'tm_express_way_name_1');
                $page_result['page_data'][$key]['tm_express_status_name'] = moe_status($page_result['page_data'][$key]['tm_express_status']);
                $page_result['page_data'][$key]['tm_express_address'] = $this->get_field_value_by_id('user_shipping_address', 'usa_id', $page_result['page_data'][$key]['usa_id'], 'usa_address');
            } else {
                $page_result['page_data'][$key]['tm_express_way_name'] = lang('msg', 'tm_express_way_name_0');
                $page_result['page_data'][$key]['tm_express_way_name'] = lang('msg', 'tm_express_status_name_0');
                $page_result['page_data'][$key]['tm_express_address'] = '';
            }
            //DEBUG 取出订单课程信息 trade_course
            $sql = "SELECT cm_id FROM " . DB::table('trade_course') . " WHERE tm_id='" . $page_result['page_data'][$key]['tm_id'] . "' LIMIT 200";
            $result = DB::fetch_all($sql);
            $cm_ids = array();
            foreach ($result AS $k => $v) {
                $cm_ids[$v['cm_id']] = $v['cm_id'];
            }
            $course_info = self::get_field_value_by_id('course_main', 'cm_id', $cm_ids, 'cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,user_id,cm_cate_id');
            foreach ($course_info AS $ckey => $cvalue) {
                $cvalue['so_name'] = $this->get_field_value_by_id('school_online', 'so_id', $cvalue['so_id'], 'so_name');
                $page_result['page_data'][$key]['tm_trade_course'][] = $cvalue;
            }
        }
        */
        //TODO 后期优化取消连表问题 有利于表分布式部署
        $sql_info = "SELECT tm.*,cm.*,cm.user_id AS t_user_id,tc.*,tc.create_dateline AS dateline FROM ".DB::table('trade_course')." AS tc LEFT JOIN ".DB::table('course_main')." AS cm ON tc.cm_id=cm.cm_id LEFT JOIN ".DB::table('trade_main')." AS tm ON tc.tm_id=tm.tm_id ".$wheresql.$orderby. DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        $sql_total_rows = "SELECT count(*) FROM ".DB::table('trade_course')." AS tc LEFT JOIN ".DB::table('trade_main')." AS tm ON tc.tm_id=tm.tm_id ".$wheresql;
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($sql_total_rows_result / $perpage)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        if ($_G['gp_api']) {
            $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
            $return['code'] = '0';
            if ($client == 'pc') {
                /*
                  var list = [
                  { id: '1', num: '123456', state: '1', price: '100', time: '2016-04-26 11:24:23', course: { id: '1', title: '走进电商走近淘宝', img: '/images/310.png', teacher: '教师名字（取前2位）', type: '1' } },
                  { id: '1', num: '123456', state: '2', price: '100', time: '2016-04-26 11:24:23', course: { id: '1', title: '走进电商走近淘宝', img: '/images/310.png', teacher: '教师名字（取前2位）', type: '2' } },
                  ]
                 */
                $order = array();
                //DEBUG 格式化PC输出
                foreach ($page_result['page_data'] AS $key => $value) {
                    $tmp = array();
                    $tmp['id'] = $value['cm_id'];
                    $tmp['tc_id'] = $value['tc_id'];
                    $tmp['title'] = $value['cm_name'];
                    $tmp['img'] = $value['cm_img'];
                    $tmp['teacher'] = ext::user_realname($value['t_user_id']);
                    $tmp['type'] = $value['cm_cate_id'];
                    $tmp['cm_price'] = $value['cm_price'];
                    $temp = array();
                    $temp['id'] = $value['tm_id'];
                    $temp['num'] = $value['tm_out_trade_no'];
                    //DEBUG 增加课程状态 合并返回给前端
                    if($value['tc_flag']==1 && $value['tc_type'] == 1){//待处理 为 退款中
                        $value['tm_all_status']=5;
//                        $value['tm_all_status']="7";
                    }
                    if($value['tc_flag']==1 && $value['tc_type'] == 2){//退款成功 为 已关闭
                        $value['tm_all_status']="7";
                    }
                    if($value['tc_flag']==1 && $value['tc_type'] == 3){//拒绝退款 为 已付款
                        $value['tm_all_status']="2";
                    }
                    if($value['tc_flag']==1 && $value['tc_type'] == 4){//已关闭 为 已关闭
                        $value['tm_all_status']="7";
                    }
                    $temp['state'] = $value['tm_all_status'];
                    $temp['time'] = date('Y-m-d H:i:s',$value['dateline']);
                    $temp['create_dateline'] = $value['dateline'];
                    $temp['tm_total_fee'] = $value['tm_total_fee'];
                    $temp['course'] = $tmp;
                    $order[] = $temp;
                }
                $page_result['page_data']=$order;
                $return['data'] = $page_result;
            } else {
                $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $page_result;
            }
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        } else {
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=trade&action=main&do=index&keyword=" . $keyword);
            include template('trade/main/index');
        }
    }

    /*
     * 申请退款列表
     */
    public function do_apply() {
        global $_G;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : '6';
        $start = (($page - 1) * $perpage);
        $tc_type = isset($_REQUEST['tc_type']) ? $_REQUEST['tc_type'] : '';
        if($tc_type){
            $wheresql = " AND tc_type='".$tc_type."' ";
        }
        else{
            $wheresql = " AND tc_type in (1, 2, 3) ";
        }
        $wheresql .= " AND user_id='" . $_G['user_id'] . "' ";
        $orderby = " ORDER BY tc_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 获取信息
        $page_result = $this->index('trade_course', $page_condition);
        $cm_ids = $tm_ids = $tc_types = array();
        foreach ($page_result['page_data'] AS $key => $value) {
            $cm_ids[$value['cm_id']] = $value['cm_id'];
            if($value['tm_id']){
                $tm_ids[$value['tm_id']] = $value['tm_id'];
                //DEBUG 获取选课退款状态
                $tc_types[$value['tm_id']] = $value['tc_type'];
            }
        }
        $course_main = $course_main_array = array();
        $course_main = self::get_field_value_by_id('course_main', 'cm_id', $cm_ids, 'cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,user_id,cm_cate_id');
        foreach ($course_main AS $ckey => $cvalue) {
            
           $course_main_array[$cvalue['cm_id']] = $cvalue;
        }
        $trade_main = $trade_main_array = array();
        $trade_main = self::get_field_value_by_id('trade_main', 'tm_id', $tm_ids);
        foreach ($trade_main AS $ckey => $cvalue) {
           $trade_main_array[$cvalue['tm_id']] = $cvalue;
        }
        if ($_G['gp_api']) {
            $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
            $return['code'] = '0';
            if ($client == 'pc') {
                $order = array();
                //DEBUG 格式化PC输出
                foreach ($page_result['page_data'] AS $key => $value) {
                    $temp = array();
                    $temp['id'] = $trade_main_array[$value['tm_id']]['tm_id'];
                    $temp['num'] = $trade_main_array[$value['tm_id']]['tm_out_trade_no'];
                    $temp['time'] = $trade_main_array[$value['tm_id']]['create_dateline'];
                    $temp['create_dateline'] = $trade_main_array[$value['tm_id']]['create_dateline'];
                    $temp['tm_total_fee'] = $trade_main_array[$value['tm_id']]['tm_total_fee'];
                    $temp['tc_type'] = $tc_types[$value['tm_id']]['tc_type'];
                    $tmp = array();
                    $tmp['id'] = $course_main_array[$value['cm_id']]['cm_id'];
                    $tmp['title'] = $course_main_array[$value['cm_id']]['cm_name'];
                    $tmp['img'] = $course_main_array[$value['cm_id']]['cm_img'];
                    $tmp['teacher'] = ext::user_realname($course_main_array[$value['cm_id']]['user_id']);
                    $tmp['type'] = $course_main_array[$value['cm_id']]['cm_cate_id'];
                    $tmp['cm_price'] = $course_main_array[$value['cm_id']]['cm_price'];
                    $temp['course'] = $tmp;
                    $order[] = $temp;
                }
                $page_result['page_data']=$order;
                $return['data'] = $page_result;
            } else {
                $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $page_result;
            }
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        } else {
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=trade&action=main&do=apply&keyword=" . $keyword);
            include template('trade/main/apply');
        }
    }

    /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $return_type string json/xml.
     *
     * @return print string json/xml.
     */
    public function do_api() {
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start = (($page - 1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if ($keyword) {
            $wheresql = " WHERE title LIKE '%" . $keyword . "%'";
        }
        $orderby = " ORDER BY tm_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
          $page_result = array(
          //int 返回结果总数
          'total_rows' => $total_rows,
          //array 一页数据数组
          'page_data' => $page_data
          );
         */
        $page_result = $this->api('trade_main', $page_condition);
        if ('json' == $return_type) {
            $return = json_encode($page_result);
        } elseif ('xml' == $return_type) {
            $return = array2xml($page_result);
        }
        //DEBUG 接口响应直接输出返回
        echo $return;
    }

}

?>